<template>
	<view
		style="position: absolute;top: 0;left: 0;right: 0;bottom: 0;background-color: #f7f7f7;display: flex;flex-direction: column;">
		<view style="flex: 1;overflow: hidden;">
			<scroll-view scroll-y="true" style="height: 100%;width: 100%;padding: 10px;box-sizing: border-box;"
				:show-scrollbar="true">
				<view style="background-color: #FFFFFF;border-radius: 10px;padding: 15px 10px 0;margin-bottom: 10px;">
					<view v-if="data.delivery == 1">
						<view style="font-weight: bold;text-align: center;">到店自提</view>
					</view>
					<view v-else>
						<view style="font-weight: bold;">送货上门</view>
					</view>
					<view style="font-weight: bold;display: flex;font-size: 14px;">
						<view style="flex: 1;">{{data.storeActiveitem.name}}</view>
						<view style="flex: 1;">{{data.storeActiveitem.phone}}</view>
					</view>
					<view v-if="data.delivery == 1">
						<u--form labelPosition="left" :model="formData" labelWidth="70" :rules="rules" ref="ruleForm1">
							<u-form-item label="联系人" prop="name">
								<u--input v-model="formData.name" placeholder="请填写您的联系姓名" border="none"></u--input>
							</u-form-item>
							<u-form-item label="联系电话" prop="phoneNumber">
								<u--input v-model="formData.phoneNumber" placeholder="请填写您的联系电话" border="none">
								</u--input>
							</u-form-item>
						</u--form>
					</view>
					<view v-else>
						<view v-if="!deafultAddress" @click="setUpAddress" style="height: 60px;display: flex;align-items: center;">
							<view style="flex: 1;">设置收货信息</view>
							<view>
								<u-icon name="arrow-right"></u-icon>
							</view>
						</view>
						<view v-else @click="setUpAddress" style="display: flex;align-items: center;">
							<view style="flex: 1;display: flex;flex-direction: column;padding: 5px 0 5px 0;height: 60px;box-sizing: border-box;">
								<view style="margin-bottom: 5px;font-weight: bold;">{{deafultAddress.name}} {{deafultAddress.phoneNumber}}</view>
								<view>{{deafultAddress.address}}</view>
							</view>
							<view>
								<u-icon name="arrow-right"></u-icon>
							</view>
						</view>
					</view>
				</view>
				<view style="background-color: #FFFFFF;border-radius: 10px;padding: 10px;margin-bottom: 10px;">
					<uni-file-picker
					    v-model="uploadFileList" 
						limit="1"
						file-mediatype="all"
					    mode="grid" 
					    @select="select" 
					    @progress="progress" 
					    @success="success" 
					    @fail="fail" 
					/>
					<view v-if="uploadFileList.length" style="padding: 5px 0;">
						<view>文件页码范围</view>
						<view style="display: flex;justify-content: flex-end;">
							<view style="flex-basis: 100px;">
								<u-radio-group
									v-model="radiovalue"
									placement="column"
									@change="groupChange"
								>
									<u-radio
										:customStyle="{marginBottom: '8px'}"
										label="全部"
										:name="0"
										@change="radioChange"
									>
									</u-radio>
									<u-radio
										:customStyle="{marginBottom: '8px'}"
										label="页码范围"
										:name="1"
										@change="radioChange"
									>
									</u-radio>
								</u-radio-group>
							</view>
							<view style="flex: 1;" class="yema">
								<u--textarea v-model="pageNumber" autoHeight  placeholder="请输入页码用逗号分割.(例:1,3,5-12)"></u--textarea>
							</view>
						</view>
						
					</view>
				</view>
				<view style="background-color: #FFFFFF;border-radius: 10px;padding: 10px;margin-bottom: 5px;">
					<view style="border-bottom: 1px solid rgba(0,0,0,0.1);padding-bottom: 5px;font-size: 14px;">
						共{{data.cardAllNumAndPrice.allNum}}件商品
					</view>
					<view v-for="item in data.cardList" :key="item"
						style="display: flex;height: 80px;align-items: center;">
						<view style="flex-basis: 80px;display: flex;align-items: center;justify-content: center;">
							<image :src="item.image ? ptUrl+item.image:'#'"
								style="width: 66px;height: 66px;"></image>
						</view>
						<view
							style="padding: 10px 0;box-sizing: border-box;height: 100%;flex: 1;display: flex;flex-direction: column;justify-content: space-around;">
							<view style="font-weight: 500;">{{item.commodityName}}</view>
							<view v-if="item.isMultiSpecification">
								<text style="color:#1c9492;font-size: 12px;border: 1.5px solid #1c9492;padding: 0.5px 2px;"
								v-for="gitem in item.groupValueList" :key="gitem.groupValueId">{{gitem.groupValueName}}</text>
							</view>
							<view v-else>
								<text style="color:#1c9492;font-size: 12px;border: 1.5px solid #1c9492;padding: 0.5px 2px;"
								>默认</text>
							</view>
							<view style="flex: 1;display: flex;align-items: flex-end;">
								<view style="flex: 1;font-size: 14px;">x{{item.num}}</view>
								<view style="font-size: 17px;">￥{{item.price*item.num}}</view>
							</view>
						</view>
					</view>
					<!-- <view style="height: 1px;background-color: rgba(0,0,0,0.1);"></view> -->
					<u-cell-group v-if="data.delivery != 1">
						<u-cell title="配送费用">
							<view slot="right-icon">￥2</view>
						</u-cell>
					</u-cell-group>
					<u--form labelPosition="left" :model="formData" labelWidth="50">
						<u-form-item label="备注" prop="orderRemarks">
							<u--textarea placeholder="请输入备注" v-model="formData.orderRemarks" count></u--textarea>
						</u-form-item>
					</u--form>
				</view>
			</scroll-view>
			<u-popup :show="addressShow" @close="addressPopupClose">
				<view style="padding: 15px 15px 10px;box-sizing: border-box;display: flex;flex-direction: column;">
					<view style="text-align: center;font-weight: bold;">选择地址</view>
					<view style="flex: 1;overflow: hidden;">
						<scroll-view scroll-y="true" style="max-height: calc( 50vh );width: 100%;" :show-scrollbar="true">
							<view v-for="(item,index) in addressList" 
								:key="item.id" @click="selectAddress(item)"
								style="display: flex;border-bottom: 1px solid #F1F1F1;padding: 10px 0;">
								<view style="display: flex;align-items: center;margin-right: 15px;">
									<u-icon name="map"></u-icon>
								</view>
								<view style="display: flex;flex-direction: column;">
									<view style="display: flex;font-weight: bold;">
										<view style="margin-right: 10px;">{{item.name}}</view>
										<view>{{item.phoneNumber}}</view>
									</view>
									<view>{{item.address}}</view>
								</view>
							</view>
						</scroll-view>
					</view>
					<view style="flex-basis: 50px;display: flex;align-items: center;">
						<u-button type="primary" shape="circle" text="新增地址" @click="addAddressClick"></u-button>
					</view>
				</view>
			</u-popup>
			<u-popup :show="addAddressShow" @close="addAddressClose" mode="center" :round="10">
				<view style="padding: 15px;box-sizing: border-box;background-color: #F4F4F5;border-radius: 10px;">
					<view style="text-align: center;font-weight: bold;">新增地址</view>
					<u--form labelPosition="left" :labelWidth="80" :model="addressInfo" :rules="rules" ref="form1">
						<u-form-item label="姓名" prop="name" borderBottom>
							<u--input v-model="addressInfo.name" border="none" placeholder="请填写姓名"></u--input>
						</u-form-item>
						<u-form-item label="联系电话" prop="phoneNumber" borderBottom>
							<u--input v-model="addressInfo.phoneNumber" border="none" placeholder="请填写电话号码"></u--input>
						</u-form-item>
						<u-form-item label="学校地址" prop="address" borderBottom>
							<u--input v-model="addressInfo.address" border="none" placeholder="请填写地址"></u--input>
						</u-form-item>
					</u--form>
					<view style="margin: 10px 0 15px 0;">
						<u-checkbox-group v-model="addressInfo.defaultAddress" placement="row">
							<u-checkbox label="设置为默认地址" :name="1"></u-checkbox>
						</u-checkbox-group>
					</view>
					<u-button type="primary" shape="circle" text="立刻保存" @click="submit"></u-button>
				</view>
			</u-popup>
		</view>
		<view
			style="flex-basis: 60px;display: flex;align-items: center;padding: 10px;box-sizing: border-box;background-color: #FFFFFF;box-shadow: 0 1px 3px 0 rgb(0 0 0 / 12%), 0 0 3px 0 rgb(0 0 0 / 4%);">
			<view style="flex: 1;">
				合计
				￥{{data.cardAllNumAndPrice.allPrice}}
			</view>
			<view style="flex-basis: 100px;">
				<u-button type="primary" shape="circle" text="去支付" @click="toPayment"></u-button>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		ptUrl
	} from '@/utils/env.js'
	export default {
		onLoad: function(option) {
			if (option.data) {
				this.data = JSON.parse(option.data);
			}
			if(this.data.delivery == 1){
				this.getUserinfo(false);
			}else{
				this.getDeafultAddress();
			}
		},
		onReady() {
			if(this.data.delivery == 1){
				this.$refs.ruleForm1.setRules(this.rules);
			}
		},
		data() {
			return {
				ptUrl:ptUrl,
				data: {},
				fileList1: [],
				formData: {
					name: "",
					phoneNumber: "",
					orderRemarks: "",
				},
				rules: {
					name: [{
							type: 'string',
							required: true,
							message: '请填写姓名',
							trigger: ['blur', 'change']
						},
						{
							min: 1,
							max: 11,
							message: '长度在1-11个字符之间'
						},
					],
					phoneNumber: [{
							type: 'string',
							required: true,
							message: '请填写电话号码',
							trigger: ['blur', 'change']
						},
						{
							pattern: /^1[3-9]\d{9}$/,
							message: '手机号码格式不正确'
						}
					],
				},
				addressList:[],
				deafultAddress:null,
				addressShow:false,
				addAddressShow:false,
				addressInfo: {
					name: "",
					phoneNumber: "",
					address: "",
					defaultAddress: []
				},
				rules: {
					name: [{
							type: 'string',
							required: true,
							message: '请填写姓名',
							trigger: ['blur', 'change']
						},
						{
							min: 1,
							max: 11,
							message: '长度在1-11个字符之间'
						},
					],
					phoneNumber: [{
							type: 'string',
							required: true,
							message: '请填写电话号码',
							trigger: ['blur', 'change']
						},
						{
							pattern: /^1[3-9]\d{9}$/,
							message: '手机号码格式不正确'
						}
					],
					address: {
						type: 'string',
						required: true,
						message: '请填写地址',
						trigger: ['blur', 'change']
					},
				},
				uploadFileList:[],
				radiovalue:0,
				pageNumber:"",
			}
		},
		computed:{
			orderCommodityList(){
				let data = []
				if(this.data.cardList)
					for (let s of this.data.cardList) {
						data.push({
							commodityDetailsId:s.commodityDetailsId,
							quantity:s.num,
							unitPrice:s.price
						})
					}
				return data;
			}
		},
		methods: {
			groupChange(n) {
				console.log('groupChange', n);
			},
			radioChange(n) {
				console.log('radioChange', n);
			},
			addOrder(data){
				this.$http("/order/addOrder","POST",data).then(res=>{
					// console.log(res)
					uni.showToast({
						title: res.data.message,
						icon: "success",
						duration: 1500
					})
					setTimeout(function () {
						uni.switchTab({
							url: '/pages/order/order'
						})
					},1500)			
				})
			},
			//去支付
			toPayment() {
				let data = {
					orderCommodityList: this.orderCommodityList,
					storeOrder:{
						storeId:this.data.storeActiveitem.storeId,
						isSelfMention:this.data.delivery,
						orderRemarks:this.formData.orderRemarks,
						fileUrl: this.uploadFileList[0] ? this.uploadFileList[0].path : null,
						fileName: this.uploadFileList[0] ? this.uploadFileList[0].name : null,
						pageNumber: this.radiovalue ? this.pageNumber:this.radiovalue,
						allPrice:this.data.cardAllNumAndPrice.allPrice,
					}
				}
				if(data.storeOrder.fileUrl == null){
					uni.$u.toast('请上传打印文件！');
					return;
				}
				//自提
				if(this.data.delivery == 1){
					data.storeOrder.orderContacts = this.formData.name
					data.storeOrder.phoneNumber = this.formData.phoneNumber
					this.$refs.ruleForm1.validate().then(res => {
						// uni.$u.toast('校验通过')
						uni.showModal({
						    title: '支付',
						    content: '是否支付?',
						    success: res => {
						        if (res.confirm) {
						            console.log('用户点击确定');
									this.addOrder(data);
						        } else if (res.cancel) {
						            console.log('用户点击取消');
						        }
						    }
						});
					}).catch(errors => {
						// console.log(errors)
						uni.$u.toast(errors[0].message)
					})
				}else{
					if(!this.deafultAddress || !this.deafultAddress.id){
						uni.$u.toast('请选择收货地址！');
						return;
					}
					data.storeOrder.addressId = this.deafultAddress.id
					uni.showModal({
					    title: '支付',
					    content: '是否支付?',
					    success: res => {
					        if (res.confirm) {
					            console.log('用户点击确定');
								this.addOrder(data);
					        } else if (res.cancel) {
					            console.log('用户点击取消');
					        }
					    }
					});
				}
			},
			//获取用户信息
			getUserinfo(refresh){
				this.$http("/wx-user/userinfo","GET",{refresh:refresh}).then(res=>{
					this.formData.name  = res.data.data.nickName
					this.formData.phoneNumber  = res.data.data.phoneNumber
				})
			},
			//获取默认地址
			getDeafultAddress(){
				this.$http("/address/getDeafultAddress", "GET", null).then(res => {
					this.deafultAddress = res.data.data
				})
			},
			//获取所有地址
			getAllAddress() {
				this.$http("/address/getAllAddress", "GET", null).then(res => {
					this.addressList = res.data.data;
				})
			},
			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1)
			},
			//打开选择地址的popup
			setUpAddress(){
				this.getAllAddress();
				this.addressShow = true;
			},
			//关闭选择地址的popup
			addressPopupClose(){
				this.addressShow = false;
			},
			//选择地址
			selectAddress(item){
				this.deafultAddress = item
				this.addressShow = false;
			},
			//关闭增加地址的popup
			addAddressClose(){
				this.addAddressShow = false
			},
			//打开增加地址的popup
			addAddressClick(){
				this.addAddressShow = true
			},
			submit() {
				this.$refs.form1.validate().then(res => {
					// uni.$u.toast('校验通过')
					uni.showLoading({
					    title: '提交中'
					});
					let data = JSON.parse(JSON.stringify(this.addressInfo));
					data.defaultAddress = data.defaultAddress[0] || 0;
					this.$http("/address/addAddress", "POST", data).then(() => {
						this.getAllAddress();
						this.addAddressClose();
						uni.hideLoading();
					})
				}).catch(errors => {
					uni.$u.toast('校验失败')
				})
			},
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					uni.uploadFile({
						url: ptUrl+'/order/upload', // 仅为示例，非真实的接口地址
						filePath: url,
						name: "file",
						header:{
							'Authorization': uni.getStorageSync('token')
						},
						success: (res) => {
							let data = JSON.parse(res.data)
							// console.log(data)
							if(data.code == 0){
								resolve(data.data)
							}else{
								reject(data.data)
							}
						}
					})
				})
			},
			clickPreview(event){
				console.log("event")
			},
			// 获取上传状态
			async select(e){
				console.log('选择文件：',e)
				this.uploadFileList = e.tempFiles;
				for (let i = 0; i <this.uploadFileList.length; i++) {
					const result = await this.uploadFilePromise(this.uploadFileList[i].url);
					console.log(result)
					this.uploadFileList[i].path = result;
				}
			},
			// 获取上传进度
			progress(e){
				console.log('上传进度：',e)
			},
			
			// 上传成功
			success(e){
				console.log('上传成功')
			},
			
			// 上传失败
			fail(e){
				console.log('上传失败：',e)
			},
		}
	}
</script>

<style scoped>
	.yema >>> textarea{
		min-height: 35px;
	}
</style>
